package com.dingreading.cloud.soms.controller;

import com.dingreading.cloud.common.base.R;
import com.dingreading.cloud.common.dto.LoginDataDto;
import com.dingreading.cloud.common.util.AccountUtil;
import com.dingreading.cloud.common.util.DescribeException;
import com.dingreading.cloud.common.util.RedisParam;
import com.dingreading.cloud.soms.dto.StoreProjectCycleDtoV2;
import com.dingreading.cloud.soms.entity.StoreProjectCycle;
import com.dingreading.cloud.soms.entity.StoreProjectCycleConfig;
import com.dingreading.cloud.soms.entity.StoreProjects;
import com.dingreading.cloud.soms.service.StoreProjectCycleConfigService;
import com.dingreading.cloud.soms.service.StoreProjectCycleService;
import com.dingreading.cloud.soms.service.StoreProjectsService;
import com.dingreading.cloud.soms.util.CmorderUtil;
import com.dingreading.cloud.soms.util.LoginInfoUtil;
import com.dingreading.cloud.soms.util.ProjectCycleUtil;
import com.dingreading.cloud.soms.util.redis.RedisService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/front/storeProjectCycle/v2")
@Api(tags = "门店-门店服务周期管理V2")
public class FrontStoreProjectCycleControllerV2 {

    @Resource
    protected StoreProjectCycleService cycleService;
    @Resource
    protected StoreProjectsService projectsService;
    @Resource
    protected StoreProjectCycleConfigService cycleConfigService;
    @Resource
    protected RedisService redisService;


    @ApiOperation(value = "获取服务的周期")
    @PostMapping(value = "/getList")
    public R<Object> getList(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "服务uid") @RequestParam(value = "projectUid") String projectUid,
            @ApiParam(value = "启用状态") @RequestParam(value = "enabled", required = false) Integer enabled
    ) {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();

        List<StoreProjectCycleDtoV2> list = cycleService.listByCycleConfig(
                AccountUtil.isSelfStore(loginDto.getCurrentOperationType()), storeUid, projectUid
        );
        return R.ok(list);
    }

    @Transactional(rollbackFor = DescribeException.class)
    @ApiOperation(value = "新增/修改")
    @PostMapping(value = "/newBean", produces = "application/json; charset=UTF-8")
    public R<Object> newBean(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "周期uid") @RequestParam(value = "uid", required = false) String uid,
            @ApiParam(value = "服务uid") @RequestParam(value = "projectUid") String projectUid,
            @ApiParam(value = "周期名称") @RequestParam(value = "cycleName") String cycleName,
            @ApiParam(value = "活动天数") @RequestParam(value = "days") Integer days,
            @ApiParam(value = "活动次数") @RequestParam(value = "lessons", required = false) Integer lessons,
            @ApiParam(value = "总价") @RequestParam(value = "totalAmount") Double totalAmount,
            @ApiParam(value = "单价") @RequestParam(value = "unitAmount") Double unitAmount
    ) throws Exception {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();

        if (StringUtils.isBlank(cycleName))
            return R.fail("周期名称不能为空");
        if (null == days || days <= 0)
            return R.fail("请填写正确的活动天数");
        if (StringUtils.isBlank(projectUid))
            return R.fail("请选择服务");
        if (totalAmount == null || totalAmount < 0)
            return R.fail("请填写正确的总价");
        if (unitAmount == null || unitAmount < 0)
            return R.fail("请填写正确的单价");

        StoreProjects projects = projectsService.getByUid(projectUid);
        if (null == projects)
            return R.fail("服务获取失败");
        if (CmorderUtil.isConsumeLesson(projects.getLessonStatus(), projects.getFreeStatus()))
            if (null == lessons || lessons <= 0)
                return R.fail("请填写正确的活动次数");

        boolean b = cycleService.haveNameV2(storeUid, uid, projectUid, cycleName);
        if (b)
            return R.fail("周期名称不能重复");

        if (StringUtils.isBlank(uid)) {
            // 获取最大的序号
            int maxOrderNum = cycleService.getMaxShowOrderV2(storeUid, projectUid) + 1;

            // 新增服务周期
            StoreProjectCycle data = ProjectCycleUtil.newCycle(
                    storeUid, projectUid, cycleName, days, lessons, totalAmount, unitAmount, maxOrderNum, 2,
                    staffUid, staffName
            );
            cycleService.saveOrUpdate(data);
        } else {
            // 修改服务周期
            StoreProjectCycle data = cycleService.getByCycleConfig(AccountUtil.isSelfStore(loginDto.getCurrentOperationType()), storeUid, uid);
            if (data == null)
                return R.fail("未查询到");
            if (!data.getEnabled().equals(1))
                return R.fail("已被禁用，启用后才能编辑");

            if (data.getSource().equals(1)) {
                // 总部
                StoreProjectCycleConfig cycleConfig = cycleConfigService.getByStoreUidAndProjectUidAndCycleUid(storeUid, data.getProjectUid(), uid);
                if (cycleConfig == null) {
                    // 新增门店服务周期配置
                    cycleConfig = ProjectCycleUtil.newCycleConfig(
                            storeUid, projectUid, data.getUid(), totalAmount, unitAmount, 1, staffUid, staffName
                    );
                    cycleConfigService.saveOrUpdate(cycleConfig);
                } else {
                    // 修改门店服务周期配置
                    if (!cycleConfig.getEnabled().equals(1))
                        return R.fail("已被禁用，启用后才能编辑");
                    cycleConfigService.updateInfo(
                            storeUid, data.getProjectUid(), uid, cycleConfig.getUid(),
                            totalAmount, unitAmount, null, staffUid, staffName
                    );
                }
            } else {
                // 门店自定义
                boolean b1 = cycleService.updateInfo(
                        storeUid, uid, cycleName, days, lessons, totalAmount, unitAmount, staffUid, staffName
                );
                if (!b1)
                    return R.fail("更新失败");
            }
        }

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE + storeUid);

        return R.ok();
    }

    @ApiOperation(value = "获取详情")
    @PostMapping(value = "/getBean", produces = "application/json; charset=UTF-8")
    public R<Object> getBean(
            HttpServletRequest request,
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "周期uid") @RequestParam(value = "uid") String uid
    ) {
        R<Object> r = LoginInfoUtil.getLoginDto(request);
        if (R.isError(r)) return r;
        LoginDataDto loginDto = (LoginDataDto) r.getData();

        StoreProjectCycle data = cycleService.getByCycleConfig(AccountUtil.isSelfStore(loginDto.getCurrentOperationType()), storeUid, uid);
        if (data == null)
            return R.fail("获取失败");

        return R.ok(data);
    }

    @ApiOperation(value = "设置启用")
    @PostMapping(value = "/updateEnabled", produces = "application/json; charset=UTF-8")
    public R<Object> updateEnabled(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "周期uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "周期名称") @RequestParam(value = "cycleName", required = false) String cycleName,
            @ApiParam(value = "活动天数") @RequestParam(value = "days", required = false) Integer days,
            @ApiParam(value = "活动次数") @RequestParam(value = "lessons", required = false) Integer lessons,
            @ApiParam(value = "总价") @RequestParam(value = "totalAmount", required = false) Double totalAmount,
            @ApiParam(value = "单价") @RequestParam(value = "unitAmount", required = false) Double unitAmount,
            @ApiParam(value = "启用/禁用") @RequestParam(value = "enabled") Integer enabled
    ) {
        StoreProjectCycle data = cycleService.getByUid(uid);
        if (data == null)
            return R.fail("获取失败");

        if (data.getSource().equals(1)) {
            // 总部
            StoreProjectCycleConfig cycleConfig = cycleConfigService.getByStoreUidAndProjectUidAndCycleUid(storeUid, data.getProjectUid(), uid);
            if (cycleConfig == null) {
                if (enabled.equals(1)) {
                    if (totalAmount == null || totalAmount < 0)
                        return R.fail("请填写正确的总价");
                    if (unitAmount == null || unitAmount < 0)
                        return R.fail("请填写正确的单价");
                }
                // 新增门店服务周期配置
                cycleConfig = ProjectCycleUtil.newCycleConfig(
                        storeUid, data.getProjectUid(), data.getUid(), totalAmount, unitAmount, enabled, staffUid, staffName
                );
                cycleConfigService.saveOrUpdate(cycleConfig);
            } else {
                if (enabled.equals(1)) {
                    if (totalAmount == null || totalAmount < 0)
                        return R.fail("请填写正确的总价");
                    if (unitAmount == null || unitAmount < 0)
                        return R.fail("请填写正确的单价");
                    // 启用
                    cycleConfigService.updateInfo(
                            storeUid, data.getProjectUid(), uid, cycleConfig.getUid(),
                            totalAmount, unitAmount, 1, staffUid, staffName
                    );
                } else {
                    // 禁用
                    cycleConfigService.updateInfo(
                            storeUid, data.getProjectUid(), uid, cycleConfig.getUid(),
                            null, null, 0, staffUid, staffName
                    );
                }
            }
        } else {
            // 门店
            if (enabled.equals(1)) {
                // 启用
                if (totalAmount == null || totalAmount < 0)
                    return R.fail("请填写正确的总价");
                if (unitAmount == null || unitAmount < 0)
                    return R.fail("请填写正确的单价");
                if (StringUtils.isBlank(cycleName))
                    return R.fail("周期名称不能为空");
                if (null == days || days <= 0)
                    return R.fail("请填写正确的活动天数");
                StoreProjects projects = projectsService.getByUid(data.getProjectUid());
                if (null == projects)
                    return R.fail("服务获取失败");
                if (CmorderUtil.isConsumeLesson(projects.getLessonStatus(), projects.getFreeStatus()))
                    if (null == lessons || lessons <= 0)
                        return R.fail("请填写正确的活动次数");

                boolean b = cycleService.setEnabled(storeUid, uid, cycleName, days, lessons, totalAmount, unitAmount, staffUid, staffName);
                if (!b)
                    return R.fail("更新失败");
            } else {
                // 禁用
                boolean b = cycleService.updateEnabledV2(storeUid, uid, 0, staffUid, staffName);
                if (!b)
                    return R.fail("更新失败");
            }
        }

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE + storeUid);

        return R.ok();
    }

    @ApiOperation(value = "删除")
    @PostMapping(value = "/dropBean", produces = "application/json; charset=UTF-8")
    public R<Object> dropBean(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "周期uid") @RequestParam(value = "uid") String uid
    ) {
        StoreProjectCycle data = cycleService.getByUid(uid);
        if (data == null)
            return R.fail("获取失败");
        if (StringUtils.isBlank(data.getStoreUid()))
            return R.fail("非门店数据，不能操作");

        long l = cycleService.dropBeanV2(storeUid, uid);
        if (l <= 0)
            return R.failDel();

        cycleConfigService.deleteByCycleUid(storeUid, uid);

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE + storeUid);

        return R.ok();
    }

    @ApiOperation(value = "上移/下移")
    @PostMapping(value = "/upOrDown", produces = "application/json; charset=UTF-8")
    public R<Object> upOrDown(
            @ApiParam(value = "公司uid") @RequestParam(value = "corpUid") String corpUid,
            @ApiParam(value = "门店uid") @RequestParam(value = "storeUid") String storeUid,
            @ApiParam(value = "门店名称") @RequestParam(value = "storeName") String storeName,
            @ApiParam(value = "员工uid") @RequestParam(value = "staffUid") String staffUid,
            @ApiParam(value = "员工名") @RequestParam(value = "staffName") String staffName,
            @ApiParam(value = "周期uid") @RequestParam(value = "uid") String uid,
            @ApiParam(value = "类型 1.上移 2.下移") @RequestParam(value = "type") Integer type
    ) {
        StoreProjectCycle data = cycleService.getByUid(uid);
        if (data == null)
            return R.fail("获取失败");
        if (StringUtils.isBlank(data.getStoreUid()))
            return R.fail("非门店数据，不能操作");

        if (type.equals(1)) {
            // 上移
            StoreProjectCycle preData = cycleService.getLtOrderNumV2(storeUid, data.getProjectUid(), data.getOrderNum());
            if (preData == null) return R.fail("已在最前");
            // 和前一条记录的序号互换
            Integer prevOrderNum = preData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            cycleService.updateOrderNum(preData.getUid(), curOrderNum, staffUid, staffName);
            cycleService.updateOrderNum(uid, prevOrderNum, staffUid, staffName);
        } else if (type.equals(2)) {
            // 下移
            StoreProjectCycle backData = cycleService.getGtOrderNumV2(storeUid, data.getProjectUid(), data.getOrderNum());
            if (backData == null) return R.fail("已在最后");
            // 和后一条记录的序号互换
            Integer backOrderNum = backData.getOrderNum();
            Integer curOrderNum = data.getOrderNum();
            // 序号互换
            cycleService.updateOrderNum(backData.getUid(), curOrderNum, staffUid, staffName);
            cycleService.updateOrderNum(uid, backOrderNum, staffUid, staffName);
        } else {
            return R.fail("类型错误");
        }

        // 清除门店服务周期缓存数据
        redisService.setNullLike(RedisParam.PROJECT_CYCLE + storeUid);

        return R.ok();
    }

}
